package org.dromara.iot.handler;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.ImageUtil;
import org.dromara.common.mqtt.handler.MqttMessageHandler;
import org.dromara.iot.domain.bo.IotElevatorEventBo;
import org.dromara.iot.domain.mq.BehaviorEvent;
import org.dromara.iot.domain.vo.IotElevatorVo;
import org.dromara.iot.enums.BehaviorEnum;
import org.dromara.iot.enums.BusinessCodeEnum;
import org.dromara.iot.enums.ElevatorEventTypeEnum;
import org.dromara.iot.service.IIotElevatorEventService;
import org.dromara.iot.service.IIotElevatorService;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;

import java.io.File;

@Slf4j
@RequiredArgsConstructor
@Service
public class BehaviorMessageHandler implements MqttMessageHandler {
    private final IIotElevatorService elevatorService;
    private final ISysOssService ossService;
    private final IIotElevatorEventService elevatorEventService;

    @Override
    public void handle(String code, MqttMessage message) {
        IotElevatorVo iotElevator = elevatorService.selectByRegisteredCode(code);
        if (iotElevator == null) {
            log.error("接收到状态消息，但电梯不存在:{}", code);
            return;
        }
        log.info("接收人员行为检测告警消息：{}", message.toString());
        BehaviorEvent behaviorEvent = JSONUtil.toBean(new String(message.getPayload()), BehaviorEvent.class);
        String imagePath = ImageUtil.generateImage(behaviorEvent.getImage());
        SysOssVo upload = ossService.upload(new File(imagePath));
        log.info("上传图片成功:{}", upload);
        BehaviorEnum behaviorEnumByCode = BehaviorEnum.getBehaviorEnumByCode(behaviorEvent.getEventType());
        if (behaviorEnumByCode == null) {
            log.error("接收到状态消息，但 elevator_event_type 不存在:{}", behaviorEvent.getEventType());
            return;
        }
        IotElevatorEventBo bo = new IotElevatorEventBo();
        bo.setElevatorId(iotElevator.getElevatorId());
        bo.setEventCode(BusinessCodeEnum.ELEVATOR_EVENT.getBusinessCode());
        bo.setElevatorName(iotElevator.getElevatorName());
        bo.setEventType(ElevatorEventTypeEnum.BEHAVIOR_ALARM_EVENT.getCode());
        bo.setReportTime(behaviorEvent.getTimestamp());
        bo.setRemark(iotElevator.getElevatorName() + " " + behaviorEnumByCode.getDesc());
        bo.setOssId(upload.getOssId());
        elevatorEventService.insertByBo(bo, true);
    }
}
